package cn.exrick.front.controller;

import cn.exrick.common.constant.CommonConstant;
import cn.exrick.common.pojo.Result;
import cn.exrick.common.utils.ResultUtil;
import cn.exrick.manager.pojo.TbAddress;
import cn.exrick.manager.pojo.TbMember;
import cn.exrick.sso.service.AddressService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

@RestController
@Api(description = "收货地址")
public class AddressController {

    @Autowired
    private AddressService addressService;

    @RequestMapping(value = "/address/list",method = RequestMethod.GET)
    @ApiOperation(value = "获得所有收货地址")
    public Result<List<TbAddress>> addressList(HttpSession session){
        TbMember member = (TbMember) session.getAttribute(CommonConstant.USER_SESSION);
        List<TbAddress> list=addressService.getAddressList(member.getId());
        return new ResultUtil<List<TbAddress>>().setData(list);
    }

    @RequestMapping(value = "/address/{id}",method = RequestMethod.GET)
    @ApiOperation(value = "通过id获得收货地址")
    public Result<TbAddress> address(@PathVariable Long id){

        TbAddress address=addressService.getAddress(id);
        return new ResultUtil<TbAddress>().setData(address);
    }

    @RequestMapping(value = "/address/update",method = RequestMethod.POST)
    @ApiOperation(value = "添加或编辑收货地址")
    public Result<Object> addAddress(TbAddress tbAddress,HttpSession session){
        TbMember member = (TbMember) session.getAttribute(CommonConstant.USER_SESSION);
        tbAddress.setMemberId(member.getId());
        tbAddress.setUpdateTime(new Date());
        int result;
        if(tbAddress.getId() == null){
            tbAddress.setCreateTime(new Date());
            result=addressService.addAddress(tbAddress);
        }else{
            result=addressService.updateAddress(tbAddress);
        }
        return new ResultUtil<Object>().setData(result);
    }

    @RequestMapping(value = "/address/del",method = RequestMethod.POST)
    @ApiOperation(value = "删除收货地址")
    public Result<Object> delAddress(Long id){
        int result=addressService.delAddress(id);
        return new ResultUtil<Object>().setData(result);
    }
}
